package com.psj.interceptor;

import cn.hutool.jwt.JWT;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("------------拦截器------------拦截方法："+requestURI);
        Cookie[] cookies = request.getCookies();
        if(null!=cookies&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if("login_token".equals(cookie.getName())){
                    String token = cookie.getValue();
                    // 密钥
                    byte[] key = "1234567890".getBytes();
                    JWT jwt = JWT.of(token);
                    // 默认验证HS265的算法
                    boolean b = jwt.setKey(key).verify();
                    if(b){
                        Object username = jwt.getPayload("username");
                        Object id = jwt.getPayload("id");

                        request.setAttribute("username",username);
                        request.setAttribute("id",id);
                        return true;//放行
                    }
                }
            }
        }

        response.sendRedirect("/user/toLogin");
        return false;//拦截
    }
}
